package cn.tedu.smartos.baseuser.controller;

import cn.tedu.smartos.base.response.JsonResult;
import cn.tedu.smartos.base.response.StatusCode;
import cn.tedu.smartos.baseuser.pojo.dto.UserSaveParam;
import cn.tedu.smartos.baseuser.pojo.dto.UserLoginParam;
import cn.tedu.smartos.baseuser.pojo.dto.UserRegisterParam;
import cn.tedu.smartos.baseuser.pojo.entity.User;
import cn.tedu.smartos.baseuser.pojo.vo.UserVO;
import cn.tedu.smartos.baseuser.service.MailService;
import cn.tedu.smartos.baseuser.service.UserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/api/v1/users/")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Autowired
    private MailService mailService;

    /**
     * author 杨平
     * 用户注册
     * @return JsonResult
     */
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    @PostMapping("register")
    public JsonResult register(@RequestBody UserSaveParam regParam) {
        log.debug("开始处理【用户注册】的请求,{}",regParam);
        userService.register(regParam);
        // 2. 自动登录：调用 login 方法获取 token 和用户信息

        // 构造登录参数
        UserLoginParam loginParam = new UserLoginParam();
        loginParam.setUsername(regParam.getUsername());
        loginParam.setPassword(regParam.getPassword());
        Map<String, Object> data = userService.login(loginParam);

        // 3. 返回数据
        return JsonResult.ok(data);
    }

    /**
     * author 杨平
     * 用户登录
     * @return JsonResult
     */
//    @ApiOperation("用户登录(密码)")
//    @ApiOperationSupport(order = 20)
//    @PostMapping("login")
//    public JsonResult login(@RequestBody UserLoginParam loginParam) {
//        log.debug("开始处理【用户登录】的请求,{}",loginParam);
//        Object data = userService.login(loginParam);
//        log.debug("用户登录成功，返回数据：{}",data);
//        data = userService.login(loginParam);
//        return JsonResult.ok(data);
//    }

    @ApiOperation("用户登录(密码)")
    @ApiOperationSupport(order = 20)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam loginParam) {
        log.debug("开始处理【用户登录】的请求,{}",loginParam);
        Map<String, Object> data = userService.login(loginParam);
        log.debug("用户登录成功，返回数据：{}", data);
        return JsonResult.ok(data);
    }

    @GetMapping("checkUsername")
    public JsonResult checkUsername(@RequestParam String username) {
        Integer count = userService.findByUsername(username);
        return JsonResult.ok(count);
    }

    @GetMapping("checkPhone")
    public JsonResult checkPhone(@RequestParam String phone) {
        Integer count = userService.countByPhone(phone);
        return JsonResult.ok(count);
    }
    @GetMapping("checkIdCard")
    public JsonResult checkIdCard(@RequestParam String idCard) {
        Integer count = userService.findByIdCard(idCard);
        return JsonResult.ok(count);
    }


    @ApiOperation("发送验证码")
    @ApiOperationSupport(order = 40)
    @GetMapping("sendCode")
    public JsonResult sendCode(@RequestParam String email) {
        // 检查是否在60秒内已经发送过
        if (redisTemplate.hasKey(email + "_limit")) {
            return new JsonResult(StatusCode.FAILED,"操作过于频繁，请稍后再试");
        }

        // 生成验证码
        String code = mailService.generateCode();

        // 存储验证码到Redis，设置5分钟过期
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

        // 设置60秒内不能再次发送
        redisTemplate.opsForValue().set(email + "_limit", "1", 60, TimeUnit.SECONDS);

        // 发送邮件
        String subject = "您的验证码";
        String content = "您的验证码是：" + code + "，5分钟内有效。";
        mailService.sendMail(email, subject, content);

        return JsonResult.ok("验证码已发送");
    }

//    @ApiOperation("验证码校验")
//    @ApiOperationSupport(order = 50)
//    @GetMapping("verifyCode")
//    public JsonResult verifyCode(@RequestParam String email, @RequestParam String code) {
//        String redisCode = (String) redisTemplate.opsForValue().get(email);
//        if (redisCode == null || !redisCode.equals(code)) {
//            return new JsonResult(StatusCode.FAILED,"验证码错误");
//        }
//        return JsonResult.ok();
//    }

    @ApiOperation("忘记密码")
    @ApiOperationSupport(order = 60)
    @PostMapping("forget")
    public JsonResult forget(Long userId,String password,String email,String code) {
        log.debug("开始处理【忘记密码】的请求,参数{},{},{},{}",userId,password,email,code);
        userService.forget(userId,password,email,code);
        return JsonResult.ok();
    }
    @ApiOperation("通过用户名获取用户信息")
    @ApiOperationSupport(order = 70)
    @GetMapping("/getUserByUsername")
    public JsonResult getUserByUsername(@RequestParam String username) {
        log.debug("开始处理【通过用户名获取用户信息】的请求,参数:{}", username);
        User user = userService.getUserByUsername(username);
        if (user == null) {
            return new JsonResult(StatusCode.USER_NOT_EXIT);
        }
        return JsonResult.ok(user);
    }



    @ApiOperation("用户信息")
    @PostMapping("/updateIdentify")
    public JsonResult updateUserInfo(@RequestBody UserSaveParam userSaveParam) {
        log.debug("开始处理【用户信息】的请求,参数{}", userSaveParam);
        userService.updateIdentify(userSaveParam);
        return JsonResult.ok();
    }
}
